# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class itcastPipeline(object):
    def open_spider(self, spider):
        if spider.name == 'itcast':
            self.file = open('itcast.json','w')

    def process_item(self, item, spider):
        if spider.name == 'itcast':
            print('itcast:', item)
            # 将 item 对象强转成字典,该操作只能在scrapy中使用
            item = dict(item)

            # 将字典数据序列化
            json_data = json.dump(item, ensure_ascii=False) + ',\n'
            # 将数据写入文件
            self.file.write(json_data)
            # 默认使用完管道之后需要将数据返回给引擎
        return item

    def close_spider(self, spider):
        if spider.name == 'itcast':
            self.file.close()

class git1Pipeline(object):
    def open_spider(self, spider):
        if spider.name == 'git1':
            self.file = open('itcast.json','w')

    def process_item(self, item, spider):
        if spider.name == 'git1':
            print('itcast:', item)
            # 将 item 对象强转成字典,该操作只能在scrapy中使用
            item = dict(item)

            # 将字典数据序列化
            json_data = json.dump(item, ensure_ascii=False) + ',\n'
            # 将数据写入文件
            self.file.write(json_data)
            # 默认使用完管道之后需要将数据返回给引擎
        return item

    def close_spider(self, spider):
        if spider.name == 'git1':
            self.file.close()
